package com.gopay.bis.nbcb.ebank.operation;

import java.util.HashMap;
import java.util.Map;


import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.nbcb.ebank.query.req.NbcbB2cQueryParam;
import com.gopay.common.domain.bank.nbcb.ebank.query.res.NbcbB2cResNetPay;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.HttpsTransport;
import com.thoughtworks.xstream.XStream;

public class NbcbB2cCertHelperQuery {
	private HttpsTransport httpTransport;
	private String queryUrl;
	/**
	 * 宁波银行B2C查询
	 * @param NbcbB2cQueryParam
	 * @return NbcbB2cResNetPay
	 * @throws GopayException 
	 */
	public NbcbB2cResNetPay queryB2C(NbcbB2cQueryParam message) throws GopayException {
		try {
			Map<String, String> param = new HashMap<String, String>();
			param.put("channelName", message.getChannelName());
			param.put("version", message.getVersion());
			param.put("reqMsg", message.getReqMsg());
			NbcbB2cResNetPay repMessage = new NbcbB2cResNetPay();
			Object messageData = new Object();
			httpTransport.setUrl(message.getQueryUrl());
			messageData = httpTransport.submit(param);
			BankLogUtils.printB2CQuerySendLog(message, param);
			repMessage = parseB2C(messageData);
			BankLogUtils.printB2CQueryBlackLog(message, repMessage);
			return repMessage;
		} catch (Exception e) {
			BankLogUtils.printB2CQueryExceptionLog(message, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
		}
	}

	/**
	 * 宁波查询后报文转换
	 * @param Object messageData
	 * @return NbcbB2cResNetPay
	 */
	private NbcbB2cResNetPay parseB2C(Object messageData) {
		String retString = null;
		if (messageData instanceof byte[]) {
			retString = new String((byte[]) messageData);
		} else if (messageData instanceof String) {
			retString = (String) messageData;
		}
		retString = retString.substring(retString.indexOf("<N"));
		NbcbB2cResNetPay message = new NbcbB2cResNetPay();
		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);
		xstream.processAnnotations(NbcbB2cResNetPay.class);
		message = (NbcbB2cResNetPay) xstream.fromXML(retString);
		return message;
	}

	

	/**
	 * 将类似charset=UTF-8解析出来,如果返回值唯空，将复制“”；
	 */
	public String getParamter(String tempStr, int i) {
		String[] str = tempStr.split("=");
		if (str.length == 1 && i == 0)
			return str[0];
		else if (str.length == 1 && i == 1)
			return "";
		else
			return str[i];
	}

	public void setHttpTransport(HttpsTransport httpTransport) {
		this.httpTransport = httpTransport;
	}

	public void setQueryUrl(String queryUrl) {
		this.queryUrl = queryUrl;
	}
}
